<template>
  <div v-if="couponBase" v-loading="loading" class="couponBase">
    <div class="coupon-info">
      <!-- 头部 -->
      <div class="app-main-top-box">
        <div class="title">券详情</div>
        <el-button size="medium" round @click="back">返回</el-button>
      </div>

      <!-- 券信息 -->
      <div class="flexRBC">
        <div>
          <div>
            <span class="coupon-name">{{ couponBase.couponName }}</span>
            &nbsp;&nbsp;
            <span class="coupon-type app-text-color-primary">{{
              couponTypeOptions[couponBase.couponType]
            }}</span>
          </div>
          <div class="coupon-id">批次号：{{ couponBase.id }}</div>
        </div>
        <div
          v-if="
            !$store.getters.banBtnList.includes(
              'BTN_MCH_COUPON_MANAGER_AND_PUT_ON'
            )
          "
        >
          <el-button
            v-if="
              couponBase.status == 1 &&
                !couponBase.channelSync &&
                ['cash_wx_busi', 'discount_wx_busi', 'cash_wx_pay'].includes(
                  couponBase.couponType
                )
            "
            size="small"
            type="primary"
            round
            @click="syncCouponChannel(couponBase.id)"
          >
            同步券渠道
          </el-button>
          <el-button
            v-else-if="couponBase.status == 1"
            size="small"
            type="primary"
            round
            @click="changeStatus('enable')"
          >启用</el-button>
          <el-button
            v-if="
              couponBase.status == 1 &&
                ((!couponBase.channelSync &&
                  ['cash_wx_busi', 'discount_wx_busi', 'cash_wx_pay'].includes(
                    couponBase.couponType
                  )) ||
                  ['cash', 'discount', 'exchange'].includes(
                    couponBase.couponType
                  ))
            "
            type="info"
            size="small"
            round
            @click="editCoupon(couponBase.id)"
          >
            修改配置
          </el-button>
          <el-button
            v-if="
              couponBase.upStatus &&
                (couponBase.status == 2 || couponBase.status == 3)
            "
            size="small"
            type="warning"
            round
            @click="changeStatus(2)"
          >
            下架
          </el-button>
          <el-button
            v-if="
              !couponBase.upStatus &&
                (couponBase.status == 2 || couponBase.status == 3)
            "
            size="small"
            round
            type="primary"
            @click="changeStatus(1)"
          >
            上架
          </el-button>
          <el-button
            v-if="couponBase.status == 2 || couponBase.status == 3"
            size="small"
            round
            type="danger"
            @click="changeStatus(3)"
          >终止活动</el-button>
          <el-button
            v-if="couponBase.status == 1"
            size="small"
            round
            type="danger"
            @click="changeStatus('delet')"
          >删除</el-button>
          <el-button
            v-if="couponBase.couponType === 'cash_wx_pay'"
            size="small"
            round
            type="danger"
            @click="downWxPayCouponVerifyRecord"
          >导出微信核销记录</el-button>
        </div>
      </div>

      <!-- tab -->
      <div class="tab">
        <el-tabs v-model="tabName">
          <el-tab-pane label="详情" name="detail" />
          <el-tab-pane
            v-if="
              couponBase.status === 2 &&
                !$store.getters.banBtnList.includes(
                  'BTN_MCH_COUPON_MANAGER_AND_PUT_ON'
                )
            "
            label="领券二维码"
            name="code"
          />
          <el-tab-pane
            v-if="
              !$store.getters.banBtnList.includes('TAB_MCH_COUPON_PUT_ON_DATA')
            "
            label="发放数据"
            name="issue"
          />
          <el-tab-pane
            v-if="
              !$store.getters.banBtnList.includes('TAB_MCH_COUPON_CONSUME_DATA')
            "
            label="核销数据"
            name="verify"
          />
          <!-- <el-tab-pane v-if="couponDetail.couponTag == 1 && couponBase.status != 1" label="报名数据" name="sign" /> -->
          <!--BTN_MCH_COUPON_PUT_ON_DATA_EXPORT-->
          <!--BTN_MCH_COUPON_CONSUME_DATA_EXPORT-->
        </el-tabs>
      </div>
    </div>

    <div v-if="couponBase">
      <CouponDetail
        v-if="tabName === 'detail'"
        :coupon-base.sync="couponBase"
        @detail="getDetail"
      />
      <CouponCode v-if="tabName === 'code'" :coupon-base.sync="couponBase" />
      <IssueRecord v-if="tabName === 'issue'" :coupon-base.sync="couponBase" />
      <VerifyRecord
        v-if="tabName === 'verify'"
        :coupon-base.sync="couponBase"
      />
      <SignRecord v-if="tabName === 'sign'" :coupon-base.sync="couponBase" />
    </div>

    <DialogEnable ref="dialogEnable" />
  </div>
</template>

<script>
import CouponDetail from './CouponDetail'
import IssueRecord from './IssueRecord'
import VerifyRecord from './VerifyRecord'
import SignRecord from './SignRecord'
import CouponCode from './CouponCode'
import DialogEnable from './DialogEnable'
import { mapGetters } from 'vuex'
import {
  couponStatus,
  syncWxCoupon,
  downWxPayCouponVerifyFile,
  couponDetail,
  newUpAndDown,
  stopCoupon,
  deleteDraft
} from '../../api/coupon'

export default {
  components: {
    CouponDetail,
    IssueRecord,
    IssueRecord,
    VerifyRecord,
    CouponCode,
    SignRecord,
    DialogEnable
  },
  data() {
    return {
      // 配置
      couponTypeOptions: {
        cash: '代金券',
        cash_wx_pay: '微信支付代金券',
        cash_wx_busi: '微信商家代金券',
        discount: '折扣券',
        discount_wx_busi: '微信商家折扣券',
        exchange: '兑换券'
      },
      resolve: null,
      reject: null,
      // 状态
      loading: false,
      // 数据
      tabName: 'detail',
      couponBase: null,
      detail: null,
      couponDetail: ''
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  activated() {},
  mounted() {},
  methods: {
    /**
     * 获取数据
     */
    // 获取
    open(row) {
      this.couponBase = row
      console.log('this.couponBase----', this.couponBase)
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },
    getDetail(val) {
      this.couponDetail = val
      this.couponBase = {
        ...this.couponBase,
        ...val
      }
    },

    /**
     * 按钮组
     */
    // 返回
    back() {
      this.resolve && this.resolve()
    },

    // 改变状态
    changeStatus(status) {
      const { couponTag, signUpEndTime, endTime } = this.couponDetail // couponTag：1商圈券 2普通券
      const signUpEndTimeStmp = new Date(signUpEndTime).getTime()
      const endTimeStmp = new Date(endTime).getTime()
      const curStamp = new Date().getTime()
      // 商圈券 - 报名过期提示
      // if (couponTag == 1 && status == 1 && curStamp > signUpEndTimeStmp) {
      // 	this.$alert('报名时间已过期请重新设置报名时间', '提示', {
      // 		confirmButtonText: '确定',
      // 		callback: action => {}
      // 	});
      // 	return;
      // }
      const statusConfig = {
        1: {
          text: '激活卡券后，顾客将可以领取/购买，点击确定按钮立即激活！',
          successMsg: '激活成功',
          status: 2,
          confirmButtonText: '确认激活'
        },
        2: {
          text: '暂停活动后，优惠券将不会继续发放，直到下一次人工重启活动！',
          successMsg: '暂停成功',
          status: 3,
          confirmButtonText: '确认暂停'
        },
        3: {
          text: '终止活动后，优惠券将不会继续发放且不可再重启，但是不会影响已经投放的优惠券！',
          successMsg: '终止成功',
          status: 4,
          confirmButtonText: '确认终止'
        },
        4: {
          text: '重启卡券活动后，顾客将可以领取/购买，点击确定按钮立即重启！',
          successMsg: '重启成功',
          status: 2,
          confirmButtonText: '确认重启'
        }
      }

      // 商圈券 - 提前终止活动
      if (couponTag == 1 && status == 3 && curStamp < endTimeStmp) {
        statusConfig[status].text =
          '当前优惠券活动时间还未结束，终止后将不影响已领取的用户使用'
      }

      // 弹窗
      if (status === 1) {
        // this.$refs.dialogEnable.open('hahahh');
        const confirmText = [
          '是否上架当前优惠券？',
          '注：上架后用户可在小程序领取'
        ]
        const newDatas = []
        const h = this.$createElement // 先用$createElement创建h函数。
        for (const i in confirmText) {
          newDatas.push(h('p', confirmText[i]))
        }
        this.$confirm('提示', {
          title: '提示',
          message: h('div', null, newDatas),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.newUpAndDownFun(status)
          })
          .catch(() => {})
        return
      } else if (status === 2) {
        const confirmText = [
          '是否下架当前优惠券？',
          '注：下架后用户不可在小程序自主领取，但商户后台可给用户发放'
        ]
        const newDatas = []
        const h = this.$createElement // 先用$createElement创建h函数。
        for (const i in confirmText) {
          newDatas.push(h('p', confirmText[i]))
        }
        this.$confirm('提示', {
          title: '提示',
          message: h('div', null, newDatas),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.newUpAndDownFun(status)
          })
          .catch(() => {})
        return
      } else if (status === 3) {
        const confirmText = [
          '是否终止当前优惠券？',
          '注：终止后将不可再次使用，并不影响已发放券的使用'
        ]
        const newDatas = []
        const h = this.$createElement // 先用$createElement创建h函数。
        for (const i in confirmText) {
          newDatas.push(h('p', confirmText[i]))
        }
        this.$confirm('提示', {
          title: '提示',
          message: h('div', null, newDatas),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.stopCouponFun()
          })
          .catch(() => {})
        return
      } else if (status === 'delet') {
        const confirmText = [
          '是否删除当前优惠券？',
          '注：删除后不可修复，请谨慎操作。'
        ]
        const newDatas = []
        const h = this.$createElement // 先用$createElement创建h函数。
        for (const i in confirmText) {
          newDatas.push(h('p', confirmText[i]))
        }
        this.$confirm('提示', {
          title: '提示',
          message: h('div', null, newDatas),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.deleteDraftFun()
          })
          .catch(() => {})
        return
      } else if (status === 'enable') {
        this.$refs.dialogEnable.open(this.couponBase).then((res) => {
          this.$notify({
            title: '成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.couponDetailFun()
        })
        return
      }

      this.$confirm(statusConfig[status].text, '提示', {
        confirmButtonText: statusConfig[status].confirmButtonText,
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      }).then(() => {
        let params = ''
        params = {
          stockId: this.couponBase.id,
          status: status
        }
        this.loading = true
        couponStatus(params)
          .then((res) => {
            this.$notify({
              title: '成功',
              message: statusConfig[status].successMsg,
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.couponBase.status = statusConfig[status].status
          })
          .catch((err) => {})
          .finally(() => {
            this.loading = false
          })
      })
    },

    // 同步渠道
    syncCouponChannel(couponId) {
      this.loading = true
      syncWxCoupon({ couponId })
        .then((res) => {
          this.$notify({
            title: '成功',
            message: '同步成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.couponBase.channelSync = true
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 跳转编辑
    editCoupon(id) {
      this.$router.push({
        name: 'CardsAndOfferEditCoupon',
        query: { mode: 'edit', id }
      })
    },

    // 导出微信核销记录
    downWxPayCouponVerifyRecord() {
      if (this.couponBase.status !== 4 && this.couponBase.status !== 5) {
        this.$message.error('待券到期后方可导出核销记录')
        return
      }
      var alink = document.createElement('a')
      alink.href =
        process.env.VUE_APP_BASE_API +
        '/couponAdmin/coupon/wxPayCouponVerifyFile?couponId=' +
        this.couponBase.id +
        '&X-BUSINESS-TOKEN=' +
        this.$store.state.user.token
      alink.download = ''
      alink.click()
      // downWxPayCouponVerifyFile({ couponId: this.couponBase.id }).then(res => {
      //   this.downloadFile(res.data)
      // }).catch((err) => {
      //   this.downloadFile(err)
      // })
    },

    // 下载文件
    downloadFile(data, fileName = '导出表格.csv') {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(
        new Blob([data], { type: 'application/vnd.ms-excel' })
      )
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
    },

    // 改变状态后的详情
    couponDetailFun() {
      couponDetail({ couponId: this.couponBase.id }).then((res) => {
        const { status, upStatus } = res.data.prototype
        this.couponBase.status = status
        this.couponBase.upStatus = upStatus
      })
    },
    // 上下架
    newUpAndDownFun(status) {
      const { id } = this.couponBase
      const params = {
        // 批次号
        couponId: id,
        // 上下架操作 1-上架 2-下架
        operation: status
      }
      newUpAndDown(params).then((res) => {
        console.log('请求上下架', res)
        this.$notify({
          title: '成功',
          type: 'success',
          duration: 2000,
          offset: 40
        })
        this.couponDetailFun()
      })
    },
    // 终止
    stopCouponFun() {
      const { id } = this.couponBase
      const params = {
        // 批次号
        stockId: id,
        status: 3
      }
      stopCoupon(params).then((res) => {
        this.$notify({
          title: '成功',
          type: 'success',
          duration: 2000,
          offset: 40
        })
        this.couponDetailFun()
      })
    },
    // 删除
    deleteDraftFun() {
      const { id } = this.couponBase
      const params = {
        // 批次号
        couponId: id
      }
      deleteDraft(params).then((res) => {
        this.$notify({
          title: '成功',
          type: 'success',
          duration: 2000,
          offset: 40
        })
        this.back()
      })
    }
    /**
     * 状态组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.coupon-info {
  ::v-deep {
    .el-tabs__header {
      margin-bottom: 0;
      background-color: #fff;
      border-radius: 0 0 5px 5px;
    }

    .el-tabs__nav-wrap::after {
      background-color: #fff;
    }

    .el-tabs__active-bar {
      height: 4px;
    }

    .el-row {
      flex-wrap: wrap;
    }

    .el-card,
    .el-card__body {
      height: 100%;
    }
  }

  padding: 24px 30px 0;
  border-radius: 5px 5px;
  background-color: #fff;
  margin-bottom: 10px;

  .coupon {
    &-name {
      font-size: 20px;
      font-weight: bold;
    }

    &-type {
      font-size: 14px;
    }

    &-id {
      margin-top: 10px;
      font-size: 14px;
      color: #909399;
    }
  }
}
</style>
